package org.tinygame.herostory;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tinygame.herostory.cmdHandle.CmdHandlerFactory;


public class ServerMain {
    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerMain.class);

    public static void main(String[] args) {
        CmdHandlerFactory.init();//初始化指令处理器工厂
        GameMsgRecognizer.init();//初始化消息识别器
        MySqlSessionFactory.init();//初始化mysql会话

        EventLoopGroup bossGroup = new NioEventLoopGroup();//负责连接的事件循环组
        EventLoopGroup workerGroup = new NioEventLoopGroup();//负责处理业务的事件循环组

        //初始化引导对象
        ServerBootstrap b = new ServerBootstrap();
        //指定group
        b.group(bossGroup,workerGroup);
        //指定channel的类型
        b.channel(NioServerSocketChannel.class);
        b.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(
                        new HttpServerCodec(),
                        new HttpObjectAggregator(65535),
                        new WebSocketServerProtocolHandler("/websocket"),
                        new GameMsgDecoder(),//自定义的消息解码器
                        new GameMsgEncoder(),//自定义的消息编码器
                        new GameMsgHandler()//自定义的消息处理器
                );
            }
        });

        try {
            //绑定12345端口，以同步的方式等待服务器启动完毕
            ChannelFuture f = b.bind(12345).sync();

            if (f.isSuccess()){
                LOGGER.info("服务器启动成功");
            }

            //以同步的方式等待服务器关闭
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
